import 'package:flutter/cupertino.dart';
import 'package:client/common/event.dart';
import 'package:client/model/chat_msg_model.dart';
import 'package:client/model/chat_item_model.dart';

class ChatListProvider extends ChangeNotifier {
  List<ChatItemModel> _list = [];
  ChatItemModel? curChat;

  ChatListProvider() {
    //切换当前聊天用户
    bus.on(EventBusSet.chatChange, (arg) {
      print("change 2");
      curChat = arg as ChatItemModel;

      //取消提醒
      if (_list.isNotEmpty) {
        for (var i = 0; i < _list.length; i++) {
          var tmp = _list[i];
          if (tmp.talkId == curChat?.talkId) {
            _list[i].infoTip = 0;
          }
        }
      }

      notifyListeners();
    });

    //增加聊天  增加新的聊天用户
    bus.on(EventBusSet.chatAdd, (arg) {
      print("chat add");
      print(arg);
      // print(arg.runtimeType);

      addListItem(arg as ChatItemModel);
      notifyListeners();
    });

    //聊天消息 增加消息提示 及 增加新聊天用户
    bus.on(EventBusSet.chatMsg, (arg) {
      print("chat msg 2");

      ChatMsgModel msgModel = arg;

      //提醒
      if (_list.isNotEmpty) {
        for (var i = 0; i < _list.length; i++) {
          var tmp = _list[i];
          if (tmp.talkId == msgModel.talkId && tmp.talkId != curChat?.talkId) {
            _list[i].infoTip = 1;
          }
        }
      }

      //新增
      var tmp = ChatItemModel();
      tmp.name = msgModel.name;
      tmp.uuid = msgModel.uuid;
      tmp.talkId = msgModel.talkId;
      tmp.online = 1;
      var infoTip = 1;
      if (tmp.talkId == curChat?.talkId) {
        infoTip = 0;
      }
      tmp.infoTip = infoTip;
      addListItem(tmp);
      notifyListeners();
    });

    //聊天用户上线
    bus.on(EventBusSet.chatroomOnline, (arg) {
      if (_list.isNotEmpty) {
        for (var i = 0; i < _list.length; i++) {
          var tmp = _list[i];
          if (tmp.uuid == arg["uuid"]) {
            _list[i].online = 1;
            notifyListeners();
          }
        }
      }
    });

    //聊天用户下线
    bus.on(EventBusSet.chatroomOffline, (arg) {
      if (_list.isNotEmpty) {
        for (var i = 0; i < _list.length; i++) {
          var tmp = _list[i];
          if (tmp.uuid == arg["uuid"]) {
            _list[i].online = 0;
            notifyListeners();
          }
        }
      }
    });
  }

  init() {
    _list = [];
    curChat = null;
  }

  List<ChatItemModel> getList() {
    return _list;
  }

  addListItem(ChatItemModel item) {
    for (var v in _list) {
      if (v.talkId == item.talkId) {
        return;
      }
    }

    _list.add(item);
  }
}
